<?php
// public/users/create.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';
require_role('admin');

global $pdo;

$errors = [];
$name = $email = $role = $status = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  verify_csrf();
  $name = trim($_POST['name'] ?? '');
  $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL) ?: '';
  $role = $_POST['role'] ?? 'employee';
  $status = $_POST['status'] ?? 'active';
  $password = $_POST['password'] ?? '';

  if ($name === '' || mb_strlen($name) < 3) $errors['name'] = 'Name must be at least 3 characters.';
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors['email'] = 'Valid email is required.';
  if (!in_array($role, ['admin','hr','trainer','employee'], true)) $errors['role'] = 'Invalid role.';
  if (!in_array($status, ['active','inactive'], true)) $errors['status'] = 'Invalid status.';
  if (mb_strlen($password) < 8) $errors['password'] = 'Password must be at least 8 characters.';

  // unique email
  if (empty($errors)) {
    $stmt = $pdo->prepare("SELECT COUNT(*) AS c FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if ((int)$stmt->fetch()['c'] > 0) $errors['email'] = 'Email already in use.';
  }

  if (empty($errors)) {
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("INSERT INTO users (name,email,password,role,status) VALUES (?,?,?,?,?)");
    $stmt->execute([$name, $email, $hash, $role, $status]);
    set_flash('success', 'User created successfully.');
    header('Location: /ldp/public/users/index.php');
    exit;
  }
}

render_header('Create User', 'users');
?>
<div class="card">
  <div class="card-body">
    <form method="post" autocomplete="off" novalidate>
      <?= csrf_field(); ?>

      <div class="form-group">
        <label class="form-required">Full Name</label>
        <input type="text" name="name" class="form-control <?= isset($errors['name'])?'is-invalid':'' ?>" value="<?= htmlspecialchars($name) ?>" autofocus>
        <?php if(isset($errors['name'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['name']) ?></div><?php endif; ?>
      </div>

      <div class="form-group">
        <label class="form-required">Email</label>
        <input type="email" name="email" class="form-control <?= isset($errors['email'])?'is-invalid':'' ?>" value="<?= htmlspecialchars($email) ?>">
        <?php if(isset($errors['email'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['email']) ?></div><?php endif; ?>
      </div>

      <div class="form-group">
        <label class="form-required">Password</label>
        <input type="password" name="password" class="form-control <?= isset($errors['password'])?'is-invalid':'' ?>">
        <?php if(isset($errors['password'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['password']) ?></div><?php endif; ?>
        <small class="form-text text-muted">Min 8 characters.</small>
      </div>

      <div class="form-row">
        <div class="form-group col-md-6">
          <label class="form-required">Role</label>
          <select name="role" class="form-control <?= isset($errors['role'])?'is-invalid':'' ?>">
            <?php foreach (['employee','trainer','hr','admin'] as $opt): ?>
              <option value="<?= $opt ?>" <?= $role===$opt?'selected':'' ?>><?= ucfirst($opt) ?></option>
            <?php endforeach; ?>
          </select>
          <?php if(isset($errors['role'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['role']) ?></div><?php endif; ?>
        </div>
        <div class="form-group col-md-6">
          <label class="form-required">Status</label>
          <select name="status" class="form-control <?= isset($errors['status'])?'is-invalid':'' ?>">
            <?php foreach (['active','inactive'] as $opt): ?>
              <option value="<?= $opt ?>" <?= $status===$opt?'selected':'' ?>><?= ucfirst($opt) ?></option>
            <?php endforeach; ?>
          </select>
          <?php if(isset($errors['status'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['status']) ?></div><?php endif; ?>
        </div>
      </div>

      <div class="d-flex justify-content-between">
        <a href="/ldp/public/users/index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        <button class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
      </div>
    </form>
  </div>
</div>
<?php render_footer(); ?>
